var cookiename_siteim_is_show_im_panel = "siteim_is_show_im_panel"; //存储是否显示聊天区
var is_show_im_panel = true; //是否显示聊天区

// 已经发送的群聊消息数
var siteim_group_chat_sent_count = 0;

// 已经接收的群聊消息数
var siteim_group_chat_received_count = 0;

// 已经显示的群聊消息数(太多的话，要删除最早的消息)
var siteim_group_chat_displayed_count = 0;

//允许显示的最大群聊消息数 (太多的话，要删除最早的消息)
var siteim_group_chat_displayed_maxcount = 500;

//聊天模式：1 群聊， 2 私聊
var chat_mode = 1;

//在线人数
var siteim_online = 0;
//channelContext.id
var channelContext_id = null;
//被跟踪的用户
var traced_curruser = null;

var ele_im_panel_swicth_icon = null;
var ele_siteim_chat_text = null;
var siteim_chat_text_isDiv = false;
var ele_siteim_chat_container = null; //聊天内容容器
var ele_layim_chat_main = null;
var $siteim_chat_text = null;
//聊天面板是否处于打开状态
var chat_panel_isopen = false;
//聊天面板是否被resize过
var chat_panel_resized = false;
//群聊区域锁屏
var siteim_lock_scroll_chat = false;

var chat_panel_width = null;
var chat_panel_height = null;
/**
 * 未读消息数
 */
var siteim_notread_count = 0;
/**
 * 显示未读消息数的html元素
 */
var ele_siteim_notread_count = null;

/**
 * 聊天面板的layer id
 */
var layer_id_chat_panel;

/**
 * 发送图片预览的layer id
 */
var layer_id_uploadimg_preview;

var siteim_pageOnlineResp;

/**
 * 获取聊天框内容
 */
function getTextOfSiteimChatText() {
	if (siteim_chat_text_isDiv) {
		return ele_siteim_chat_text.innerHTML;
	} else {
		return ele_siteim_chat_text.value;
	}
}
/**
 * 设置聊天框内容
 */
function setTextOfSiteimChatText(value) {
	if (siteim_chat_text_isDiv) {
		ele_siteim_chat_text.innerHTML = value;
	} else {
		ele_siteim_chat_text.value = value;
	}
}

/**
 * 设置聊天面板高度
 */
function siteim_setChatPanelHeight() {
	// var h = getViewPortHeight() - $("#siteim_chat_panel_wrap").offset().top - 3;
	// h = Math.max(h, 200);
	// $("#siteim_chat_panel_wrap").css("height", h + "px");

	// var h = getViewPortHeight() - $("#siteim_online_wrap").offset().top - 1;
	// h = Math.max(h, 200);
	// $("#siteim_online_wrap").css("height", h + "px");
}

/**
 * 聊天右键菜单
 */
function siteim_chat_contextAction(mid, groupid) {
	this.unSend = function () {
		var req = {
			mid: mid,
			g: groupid
		};
		siteim.send(SiteImCommand.UNSEND_MSG_REQ, req);
	};
}



$(function () {
	ele_im_panel_swicth_icon = document.getElementById("im_panel_swicth_icon");
	ele_siteim_chat_text = document.getElementById("siteim_chat_text_1");
	ele_siteim_chat_container = document.getElementById("siteim_chat_container");
	ele_layim_chat_main = document.getElementById("layim_chat_main");
	ele_siteim_notread_count = document.getElementById("siteim_notread_count");
	$siteim_chat_text = $("#siteim_chat_text");






	if (
		ele_siteim_chat_text.tagName.toLocaleUpperCase() ==
		"div".toLocaleUpperCase()
	) {
		siteim_chat_text_isDiv = true;
	}

	//右键菜单
	context.init({ preventDoubleContext: false });

	if (!curruser) {
		$("#siteim_tool_div").css("display", "none");
		$("#siteim_chat_text").css("display", "none");

		$("#siteim_send_btn").html("登 录");
		$("#siteim_send_btn").css("width", "100%").css("margin-left", "0px");

		// $("#siteim_send_btn").attr("class", "layui-btn layui-btn-primary");
		// $(".siteim_chat_panel_content").css("height", "calc(100% - 40px + 3px)");

		$(".siteim_chat_panel_content").css("height", "calc(100% - 40px + 11px)");

		//height: calc(100% - 40px - 17px);
	}

	var showStr = tio.cookie.getLast(cookiename_siteim_is_show_im_panel);
	if (showStr && showStr == 2) {
	} else {
		siteim.showChatPanel();
		// siteim_init_emoji();//初始化表情符
	}

	/**
		   * 窗口大小调整时，重新调整聊天面板的大小
		   */
	$(window).resize(function () {
		siteim_setChatPanelHeight();
	});

	$(document).scroll(function () {
		siteim_setChatPanelHeight();
	});

	/**
	 * 选视频文件
	 */
	$(".siteim_uploadvideo_btn").click(function () {
		$("#siteim_uploadvideo_" + chat_mode)[0].click();
	});

	/**
	 * 选视频文件
	 */
	$(".siteim_uploadvideo").change(function () {
		var files = $("#siteim_uploadvideo_" + chat_mode)[0].files;
		var len = files.length;
		if (len > 0) {
			if (len > 9) {
				layer.alert("一次最多可以上传9个视频");
				return;
			}

			var fd = new FormData();
			for (var index = 0; index < len; index++) {
				var file = files[index];
				fd.append("uploadFile", file);
			}

			if (chat_mode == 1) {
				fd.append("groupid", siteim.groupid);
			} else {
				fd.append("touid", p2p_touser.i);
			}
			fd.append("cid", channelContext_id);

			ajax.post("/im/uploadvideo", {
				data: fd,
				contentType: false, // 注意这里应设为false
				processData: false,
				timeout: 500000,
				success: function (resp) {
					if (resp.ok) {
						//$('#finalImg').prop('src', resp.data); //显示为图片的形式
						// layer.msg("发送成功");
						// layer.close(index);
					} else {
						layer.alert(resp.msg);
					}
				}
			});
		}
	});

	/**
		   * 选择图片（可多选）上传
		   */
	$(".siteim_uploadimgs").change(function () {
		var $img_preview_container = $("#siteim_upload_imgs_preview");
		$img_preview_container.html(""); //先清空

		var fd = new FormData();
		
		var files = $("#siteim_uploadimgs_" + chat_mode)[0].files;
		var len = files.length;
		if (len > 0) {
			if (len > 9) {
				layer.alert("一次最多可以上传9张图片");
				return;
			}
			//处理九宫格
			if (len == 1) {
				$img_preview_container.css("grid-template-columns", "repeat(1, 1fr)");
			} else if (len <= 6) {
				$img_preview_container.css("grid-template-columns", "repeat(2, 1fr)");
			} else {
				$img_preview_container.css("grid-template-columns", "repeat(3, 1fr)");
			}

			var callCount = 0;
			var readers = [];
			for (var i = 0; i < len; i++) {
				var file = files[i];
				var reader = new FileReader();
				readers[i] = reader;
				reader["tiofile"] = file;
				reader.onload = function (evt) {
					callCount++;

					$img_preview_container[0].innerHTML +=
						'<div class="box"><img src="' + evt.target.result + '"/></div>';

					//当所有的回调都调用了时，显示预览框
					if (callCount == files.length) {
						$img_preview_container.html(""); //清空重新渲染
						for (var index = 0; index < len; index++) {
							var _reader = readers[index];
							fd.append("uploadFiles", _reader["tiofile"]);
							$img_preview_container[0].innerHTML +=
								'<div class="box"><img src="' + _reader.result + '"/></div>';
						}

						//
						if (layer_id_uploadimg_preview) {
							layer.close(layer_id_uploadimg_preview);
						}

						if (chat_mode == 1) {
							fd.append("groupid", siteim.groupid);
						} else {
							fd.append("touid", p2p_touser.i);
						}
						fd.append("cid", channelContext_id);


						var send_imgs = function () {
							ajax.post("/im/uploadimgs", {
								data: fd,
								contentType: false, // 注意这里应设为false
								processData: false,
								timeout: 500000,
								success: function (resp) {
									if (resp.ok) {
										//$('#finalImg').prop('src', resp.data); //显示为图片的形式
										// layer.msg("发送成功");
										layer.close(index);
										layer_id_uploadimg_preview = null;
									} else {
										layer.alert(resp.msg);
									}
								}
							});
						}

						if (chat_mode == 1) {
							layer_id_uploadimg_preview = layer.open({
								title: "发送预览",
								type: 1,
								id: 897,
								offset: "auto",
								// scrollbar : false,
								area: ["450px", "450px"], //'450px',//['450px', '450px'],
								isOutAnim: false, //禁用关闭动画，否则前面关闭再打开时会有问题
								content: $("#siteim_upload_imgs_preview_wrap"),
								btn: ["发 送", "重 选", "关 闭"],
								yes: function (index, layero) {
									// ajax.post("/im/uploadimgs", {
									// 	data: fd,
									// 	contentType: false, // 注意这里应设为false
									// 	processData: false,
									// 	timeout: 500000,
									// 	success: function (resp) {
									// 		if (resp.ok) {
									// 			//$('#finalImg').prop('src', resp.data); //显示为图片的形式
									// 			// layer.msg("发送成功");
									// 			layer.close(index);
									// 			layer_id_uploadimg_preview = null;
									// 		} else {
									// 			layer.alert(resp.msg);
									// 		}
									// 	}
									// });

									send_imgs();
								},
								btn2: function (index, layero) {
									$("#siteim_uploadimgs_" + chat_mode)[0].click();
									return false;
								},
								btn3: function (index, layero) {
									layer_id_uploadimg_preview = null;
								},
								cancel: function (index, layero) {
									layer_id_uploadimg_preview = null;
								}
							});
						} else {  //私聊
							// $("#siteim_uploadimgs_" + chat_mode)[0].click();
							send_imgs();
						}
						
					}
				};
				reader.readAsDataURL(file);
			}
		} else {
			//没选择文件则关闭layer
			if (layer_id_uploadimg_preview) {
				layer.close(layer_id_uploadimg_preview);
			}
		}
	});
});

/**
 * 显示群聊天面板
 */
siteim.showChatPanel = function () {
	siteim_setChatPanelHeight();
};

/**
 * 发送群聊
 */
siteim.groupChat = function () {
	// if (!tt.validateId('siteim_chat_text')) {
	// 	return false;
	// }


	if (!curruser) {
		try {
			tiosite_show_login(1);
			return;
		} catch (error) { }
	}

	var text = getTextOfSiteimChatText();

	var req = {
		g: siteim.groupid,
		c: text
	};
	siteim.send(SiteImCommand.GROUP_CHAT_REQ, req);

	setTextOfSiteimChatText("");
};

/**
 * 加入群组请求
 */
siteim.joinGroup = function() {
	siteim.updateGroupid();
	ele_siteim_chat_container.innerHTML = '';
	var joinGroupReq = {
		g: siteim.groupid, //encodeURIComponent(location.pathname),
		c: self.join_group_count++
	};
	siteim.send(SiteImCommand.JOIN_GROUP_REQ, joinGroupReq);

	siteim_notread_count = 0;
};

/**
 * 群聊天输入框架的回车事件
 */
siteim.chat_text_keyup = function (event) {
	if (/** event.ctrlKey && */ event.keyCode == 13) {
		siteim.groupChat();
	}
};

/**
 * 群聊自动滚屏
 */
siteim.scroll_chat = function () {
	if (!siteim_lock_scroll_chat) {
		//不锁屏才自动滚屏
		ele_layim_chat_main.scrollTop = ele_layim_chat_main.scrollHeight;
	}
};

/**
 * 图片卡片，点击时用layer来查看相册
 */
siteim.cardimg_click = function (photos_options) {
	this.h = function () {
		layer.photos(photos_options);
	};
};

/**
 * 视频卡片，点击时用layer来查看视频
 */
siteim.cardvideo_click = function (options) {
	this.h = function () {
		layer.open(options);
	};
};

/**
 * 发指令拉取在线用户(点击在线人数时会触发此函数)
 */
siteim.pull_group_online = function (g, pageNumber, pageSize, type) {
	// if ($("#siteim_online_wrap")[0].style.display == "") {
	// 	$("#siteim_online_wrap").css("display", "none");
	// 	return;
	// }

	// if (siteim_pageOnlineResp) {
	// 	siteim.show_online_list();
	// 	return;
	// }

	var req = {
		g: g, //encodeURIComponent(location.pathname),
		pageNumber: pageNumber,
		pageSize: pageSize,
		type: type
	};
	siteim.send(SiteImCommand.PAGE_ONLINE_REQ, req);
};

/**
 * 渲染一个用户到用户列表
 */
siteim.render_one_user_to_userlist = function ($ul, simpleuser) {
	var u = simpleuser; //all.list[i];
	var nick = u.n || "游客";
	if (isSuper && u.may) {
		u = u.may;
		nick = "[已登出]" + u.n;
	}
	
	var uid = u.i;

	var ipInfo = u.ipInfo;
	var cid = u.cid;
	var avatar = u.a || "/img/default-avatar.jpg";
	

	var timeJoinGroup = formatDateByTime(u.timeJoinGroup, "hh:mm:ss");
	if (
		formatDateByTime(u.timeJoinGroup, "MM-dd") !=
		formatDateByTime(Date.parse(new Date()), "MM-dd")
	) {
		timeJoinGroup = formatDateByTime(u.timeJoinGroup, "MM-dd hh:mm:ss");
	}

	// if (!uid) {   //没有登录
	// 	avatar = "/img/default-avatar.jpg";
	// 	nick = "游客";
	// }

	avatar = res_url(avatar);

	var $li = $("<li style='position: relative;'></li>");
	//   $ul.prepend($li);
	$ul.append($li);
	$li.attr("id", "userlist_" + cid);
	$li.css("box-sizing", "content-box"); //因为box-sizing: border-box;的原因，这里把高度调高一些


	var $img = $("<img />");
	$li.append($img);
	$img.attr("src", avatar);

	//显示私聊
	$img.click(function() {
		if (uid) {
			siteim.show_p2p_layer(u);
		}
	});

	var $vip = createVipFlag(u.r);
	if ($vip) {
		$li.append($vip);
		$vip.addClass("vip_to_avatar_for_online");
	}

	var v;

	var $span = $("<span></span>");
	$li.append($span);
	$span.addClass("online_userinfo_row");
	var $div11 = $("<div></div>");
	$span.append($div11);
	$div11.addClass("layui-elip");
	$div11.html(nick);

	$div11 = $("<div></div>");
	$span.append($div11);
	$div11.addClass("layui-elip");
	
	if (isSuper) {
		if (u.groupid) {
			$div11.html('<a href="' + u.groupid + '" target="_blank">' + u.groupid + '</a>');
		} else {
			$div11.html('到处乱逛');
		}
	} else {
		$div11.html('');
	}
	

	$div11 = $("<div></div>");
	$span.append($div11);
	$div11.addClass("layui-elip");
	if (isSuper) {
		if (u.userAgent && u.userAgent.agentName) {
			v = u.userAgent.agentName + u.userAgent.agentVersionMajor + " "  + u.userAgent.osName + u.userAgent.osVersion;
			$div11.html(v);
			$div11.attr("title", v);
		} else {
			$div11.html(u.mobileInfo.deviceinfo); //mobileInfo
		}
	}

	var $p = $("<p></p>");
	$li.append($p);
	$p.addClass("online_userinfo_row");

	var $div22 = $("<div></div>");
	$p.append($div22);
	$div22.addClass("layui-elip");

	if (isSuper) {
		if (uid) {
			$div22.html(u.ln);
			$div22.attr("title", u.ln);
		}
	}

	$div22 = $("<div></div>");
	$p.append($div22);
	$div22.addClass("layui-elip");
	v = "";
	if (isSuper) {
		v = ipInfo.province + ipInfo.city + ipInfo.operator || "未知";
		v = '<a href="https://www.baidu.com/s?wd=' + ipInfo.ip + '&from=t-io" target="_blank">' + v + '</a>';
		$div22.attr("title", ipInfo.ip);
	}

	$div22.html(v);
	

	$div22 = $("<div></div>");
	$p.append($div22);
	$div22.addClass("layui-elip");
	if (isSuper) {
		$div22.html(timeJoinGroup);
	}

	// var $xx = $('<p></p><span class="layim-msg-status">new</span>');
	// $li.append($xx);
};
/**
 * 显示在线用户
 */
siteim.show_online_list = function () {
	if (siteim_pageOnlineResp && siteim_pageOnlineResp.all) {
		var all = siteim_pageOnlineResp.all;

		if ($("#siteim_online_wrap")[0].style.display == "") {
			all.list.sort(siteim.sort_online_list);
			var $ul = $("#siteim_online_list_ul");
			$ul.html("");
			var ul = $ul[0];

			for (var i = 0; i < all.list.length; i++) {
				var u = all.list[i];
				siteim.render_one_user_to_userlist($ul, u);
			}
		}
	}
};
/**
 * 在线用户列表排序
 */
siteim.sort_online_list = function (a, b) {
	var mycompare = function (c, d) {
		if (isSuper) {
			if (c.timeJoinGroup > d.timeJoinGroup) {
				return -1;
			} else if (c.timeJoinGroup < d.timeJoinGroup) {
				return 1;
			} else {
				return c.cid.localeCompare(d.cid);
			}
		}
		return c.cid.localeCompare(d.cid);
	};

	if (a.may && isSuper) {
		a = a.may;
	}
	if (b.may && isSuper) {
		b = b.may;
	}

	if (isSuper) {  //如果是超管，只按时间排序
		return mycompare(a, b);
	}

	var u1 = a.i; //用户id
	var u2 = b.i;

	if (isBlank(u1) && isBlank(u2)) {    //都是未登录的游客
		return mycompare(a, b);
	} else if (!isBlank(u1) && isBlank(u2)) {
		return -1;
	} else if (isBlank(u1) && !isBlank(u2)) {
		return 1;
	} else {
		if (u1 == u2) {
			return mycompare(a, b);
		}

		//企业标识
		var isDoc1 = containRole(a.r, roles.paid_doc);
		var isDoc2 = containRole(b.r, roles.paid_doc);
		if (isDoc1 && !isDoc2) {
			return -1;
		} else if (!isDoc1 && isDoc2) {
			return 1;
		}

		//阅读权限标识
		isDoc1 = containRole(a.r, roles.allow_read_doc);
		isDoc2 = containRole(b.r, roles.allow_read_doc);
		if (isDoc1 && !isDoc2) {
			return -1;
		} else if (!isDoc1 && isDoc2) {
			return 1;
		}

		return mycompare(a, b);
	}
};
/**
 * 从在线列表中删除指定用户
 */
siteim.delete_from_online_list = function (simpleuser) {
	if (siteim_pageOnlineResp && siteim_pageOnlineResp.all) {
		siteim_pageOnlineResp.all.list = $.grep(
			siteim_pageOnlineResp.all.list,
			function (value, index) {
				return value.cid != simpleuser.cid;
			}
		);
	}
};
/**
 * 把用户添加到数组中
 */
siteim.add_to_online_list = function (simpleuser) {
	if (siteim_pageOnlineResp && siteim_pageOnlineResp.all) {
		siteim.delete_from_online_list(simpleuser);
		siteim_pageOnlineResp.all.list.push(simpleuser);
	}
};




<#include "/im/site/p2p.js" >


